let express = require('express');
let router = express.Router();
let moment = require('moment');
const assert = require('assert');

let _data_history = [];
let db = require('./db');
const Op = db.Sequelize.Op;

const unit = ['F1切帽', 'F1加工', 'F1正面', 'F1涂装半成品', 'F1涂装成品', 'F2涂装成品',
  'F1亚克力入口', 'F1亚克力出口', 'F2旋压', 'F2加工', 'F1旋压'];

const unit_new = ['F1铸造1线', 'F1铸造2线', 'F2铸造1线', 'F2铸造2线', 'F1铸造2线边浇',
  'F1热处理1线', 'F1热处理2线', 'F1加工_分立', 'F2热处理', 'F2加工_分立'];

/* 首页 */
router.get('/', function (req, res, next) {
  let data_area_1 = [];
  let data_area_2 = [];
  console.log('index page...');
  // 取时间
  let dt_today = moment();
  let dt_yestoday = moment().subtract(1, 'days');
  let hours = dt_today.get('H');
  if (hours >= 0 && hours < 8) {
    dt_today.subtract(1, 'days');
    dt_yestoday.subtract(1, 'days');
  }

  (async () => {
    let data = await day_data(dt_today);
    let d_1 = data;

    data = await day_data(dt_yestoday);
    let d_1_0 = data;

    // 计数 1
    for (let k of unit) {
      try {
        data_area_1.push({
          'k': k,
          'id': d_1[k].id,
          'dy': d_1[k].day,
          'nt': d_1[k].night,
          'total': d_1[k].total,
          'dy_0': d_1_0[k].day,
          'nt_0': d_1_0[k].night,
          'total_0': d_1_0[k].total,
        });
      } catch (err) {
        console.log(err + k);
        continue;
      }
    }
    //console.log(data_area_1);

    // 计数 2
    for (let k of unit_new) {
      try {
        data_area_2.push({
          'k': k,
          'id': d_1[k].id,
          'dy': d_1[k].day,
          'nt': d_1[k].night,
          'total': d_1[k].total,
          'dy_0': d_1_0[k].day,
          'nt_0': d_1_0[k].night,
          'total_0': d_1_0[k].total,
        });
      } catch (err) {
        console.log(err + k);
        continue;
      }
    }
    //console.log(data_area_2);

    // 渲染
    res.render('index', {
      title: '生产计数',
      data_area_1: data_area_1,
      data_area_2: data_area_2
    });
  })();
});

// 压力： 实时
router.get('/p', function (req, res, next) {
  res.render('pressure', { title: '空压机压力：实时' });
});

// 压力： 历史
router.get('/p/history', function (req, res, next) {
  res.render('pressure_history', {
    title: '空压机压力：历史'
  });
});

router.get('/p/history/:ts', function (req, res, next) {
  // 初始 0:00-至今  
  let tm = {};
  let m_date = null;
  if (req.params.hasOwnProperty('ts')) {
    let ts = req.params.ts;
    if (ts == 0) {
      tm = new Date();
      m_date = moment().format('YYYY/MM/DD');
    }
    else {
      tm = new Date(ts);
      m_date = moment().subtract(1, 'days').format('YYYY/MM/DD');
    }
  }
  console.log(tm);
  //let tm_start = new Date(tm.getFullYear(), tm.getMonth(), tm.getDate());
  let tm_start = new Date(tm.getFullYear(), tm.getMonth(), tm.getDate());
  let tm_end = new Date(tm_start);
  tm_end.setDate(tm_end.getDate() + 1);

  let data_1 = [];
  let data_2 = [];
  let data_3 = [];

  // 查询
  db.Pressure.findAll({
    where: {
      ts: {
        [Op.between]: [tm_start, tm_end]
      }
    }
  }).then(projects => {
    for (let p of projects) {
      let ts = p.dataValues.ts.valueOf() + 8 * 3600 * 1000;
      let nm = p.dataValues.number;
      switch (p.dataValues.type) {
        case "Line_1":
          data_1.push([ts, nm]);
          break;
        case 'Line_2':
          data_2.push([ts, nm]);
          break;
        case 'Line_3':
          data_3.push({ x: ts, y: nm });
          break;
      }  // switch
    }  // for

    res.json({
      data_1: data_1,
      data_2: data_2,
      data_3: data_3,
      datetime: m_date
    });
  });

});

// 热处理风机 电机状态
router.get('/f1_t4_6_motor', function (req, res, next) {
  let motor_name = {
    1: 'T4 1#',
    2: 'T4 2#',
    3: 'T4 3#',
    4: 'T4 4#',
    5: 'T4 5#',
    9: 'T6 1#',
    10: 'T6 2#',
    11: 'T6 3#',
    12: 'T6 4#',
    13: 'T6 5#',
    14: 'T6 6#',
  };
  res.render('f1_t4-6_fan', {
    title: 'F1 T4 T6风机',
    motors: motor_name,
  });
});


set_history = function (data) {
  _data_history = data;
}


async function day_data(dt) {

  let data = {};
  // 时间计算
  let yr = dt.get('year');
  let mn = dt.get('month') + 1;
  let day = dt.get('date');

  let dt_Str = `${yr}-${mn}-${day} 07`;
  // 白班7点开始
  let day_start = moment(dt_Str, 'YYYY-M-D HH');
  // 白班20点前结束
  dt_Str = `${yr}-${mn}-${day} 20`;
  let day_end = moment(dt_Str, 'YYYY-M-D HH');
  // 夜班20点开始
  let night_start = moment(dt_Str, 'YYYY-M-D HH');
  // 夜班8点前结束，加1天
  dt_Str = `${yr}-${mn}-${day} 08`;
  let night_end = moment(dt_Str, 'YYYY-M-D HH').add(1, 'days');

  // 初始化data
  let unit_all = unit.concat(unit_new);
  for (let k of unit_all) {
    let factory = 1;
    if (k.startsWith('F2')) {
      factory = 2;
    }
    data[k] = {
      'type': k,
      'day': 0,
      'night': 0,
      'total': 0,
      'factory': factory,
      'id': k,
    };
  }
  
  console.log('开始查询...');

  await db.Logger.findAll({
    attributes: ['type', [db.sequelize.fn('MAX', db.sequelize.col('number')), 'sum'], 'factory'],
    where: {
      ts: {
        [Op.between]: [day_start, day_end]
      }
    },
    group: [['type'], ['factory']]
  })
    .then(projects => {
	  console.log('查询1 结束...');	
      if (projects.length > 0) {
        for (let i = 0; i < projects.length; i++) {
          let m_id = projects[i].dataValues['type'];
          if (!m_id.startsWith('F2')) {
            m_id = 'F' + projects[i].dataValues['factory'] + m_id;
          }

          data[m_id] = {
            'type': projects[i].dataValues['type'],
            'day': projects[i].dataValues['sum'],
            'night': 0,
            'total': 0,
            'factory': projects[i].dataValues['factory'],
            'id': m_id,
          };
        }
      } // if no data
    });

  await db.Logger.findAll({
    attributes: ['type', [db.sequelize.fn('MAX', db.sequelize.col('number')), 'sum'], 'factory'],
    where: {
      ts: {
        [Op.between]: [night_start, night_end]
      }
    },
    group: [['type'], ['factory']]
  })
    .then(projects => {
	  console.log('查询2 结束...');	
      if (projects.length > 0) {
        for (let i = 0; i < projects.length; i++) {
          let m_id = projects[i].dataValues['type'];
          if (!m_id.startsWith('F2')) {
            m_id = 'F' + projects[i].dataValues['factory'] + m_id;
          }

          if (unit_all.indexOf(m_id) == -1) {
            console.log('不存在的：' + m_id);
            continue;
          }

          try {
            data[m_id]['total'] = projects[i].dataValues['sum'];
            data[m_id]['night'] = data[m_id]['total'] - data[m_id]['day'];
          } catch (err) {
            console.log('L182: ' + err);
            console.log(mid);
          }
        }
      } // if no data
    });

  //console.log(data);
  return data;
}


module.exports = router;
